package com.hxzy.projectssmplus.conf;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * springmvc前端配置文件 ，相当于之前springmvc的  xx-servlet.xml
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {
    /**
     * 以前xml这样配的
     * <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
     *                解决中文乱码
     *                 <property name="supportedMediaTypes">
     *                     <list>
     *                         <value>text/html; charset=UTF-8</value>
     *                         <value>application/json;charset=UTF-8</value>
     *                     </list>
     *                 </property>
     *             </bean>
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //添加fastjson的转换器
        FastJsonHttpMessageConverter  fastJsonHttpMessageConverter=new FastJsonHttpMessageConverter();
        //解决fastjson中文乱码
        List<MediaType> supportedMediaTypes=new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);

        //把fastjson放到 jackson2前面 ，默认的sprintboot帮你配制了10个MessageConverter
        //下标8-9时候，帮你jsonson2，必须要把fastjson放到下标在0-6位置都可以
        converters.add(0,fastJsonHttpMessageConverter);

    }



    //Filter实现CORS
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        //Access-Control-Allow-Credentials
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }



}
